<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Hash;

/**
 * 管理员
 *
 * @SWG\Model(id="Admin")
 * @SWG\Property(name="id",type="integer",description="主键索引")
 * @SWG\Property(name="avatar",type="UserFile",description="头像")
 * @SWG\Property(name="username",type="string",description="用户名")
 * @SWG\Property(name="realname",type="string",description="姓名")
 * @SWG\Property(name="mobile",type="string",description="手机号")
 * @SWG\Property(name="email",type="string",description="邮箱")
 * @SWG\Property(name="roles",type="array",items="$ref:Role",description="所属角色")
 * @SWG\Property(name="created_at",type="date-format",description="创建时间")
 */
class Admin extends Model implements AuthenticatableContract
{
	use Authenticatable, SoftDeletes;

	protected $table = 'admins';

	public static function boot()
	{
		parent::boot();

		static::saving(function ($model)
		{
			// 保存的时候自动对密码进行加密。
			if (isset($model->password) && Hash::needsRehash($model->password)) {
				$model->password = Hash::make($model->password);
			}

		});
	}

	/**
	 * 头像
	 */
	public function avatar()
	{
		return $this->belongsTo('App\Models\UserFile', 'avatar_id');
	}

	/**
	 * email 转为string类型
	 *
	 */
	public function getEmailAttribute()
	{
		return (string) $this->attributes['email'];
	}

	/**
	 * 角色列表
	 */
	public function roles()
	{
		return $this->belongsToMany('App\Models\Role', 'admin_role')->withTimestamps();
	}

	/**
	 * 菜单
	 * @return mixed
	 */
	public function getMenusAttribute()
	{
		if (! isset($this->attributes['menus'])) {
			$this->attributes['menus'] = [];
			foreach ($this->roles as $item) {
				$this->attributes['menus'] = array_merge($this->attributes['menus'], $item->menu_array);
			}
			$this->attributes['menus'] = array_values(array_unique($this->attributes['menus']));
		}
		return $this->attributes['menus'];
	}

}
